package com.yz.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * <p>
 * User:Mr.Du
 * Date:2024/4/10
 * Time:20:26
 */
@Slf4j
public class ExcelUtils {

    public static String excelToCSV(MultipartFile multipartFile, String fileType){
        ExcelTypeEnum excelTypeEnum = null;
        if("xlsx".equals(fileType)){
            excelTypeEnum = ExcelTypeEnum.XLSX;
        }else if("xls".equals(fileType)){
            excelTypeEnum = ExcelTypeEnum.XLS;
        }else if("csv".equals(fileType)){
            excelTypeEnum = ExcelTypeEnum.CSV;
        }
        // 读取数据
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(excelTypeEnum)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("csv转换错误", e);
        }
        System.out.println(list);
        if(CollUtil.isEmpty(list)){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        // 转换为csv
        // 读取表头
        LinkedHashMap<Integer,String> headerMap = (LinkedHashMap<Integer, String>) list.get(0);
        List<String> headerList = headerMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        System.out.println(StringUtils.join(headerList, ','));
        sb.append(StringUtils.join(headerList, ',')).append("\n");
        for(int i = 1;i < list.size();i++){
            LinkedHashMap<Integer,String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);
            List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            sb.append(StringUtils.join(dataList, ',')).append("\n");
            System.out.println(StringUtils.join(dataList, ','));
        }
        return sb.toString();
    }
}
